<?php
namespace app\api\logic;
use app\common\logic\{AccountLogLogic};
use app\common\model\{User, WithdrawApply,AccountLog,DevVehicleModel,Order,DevVehicleLength};
use app\common\model\ShopConfig;
use app\common\model\UserFund;
use think\Db;
use think\Exception;
use tools\GeTui;
use tools\AlipaySdk;
use tools\PayApi;
/**
 * 提现
 * Class WithdrawLogic
 * @package app\api\logic
 */
class WithdrawLogic
{

    //申请提现
    public static function apply($user_id, $post)
    {
        Db::startTrans();
        try{
            $user = User::get($post['user_id']);
            $where[] = ['user_id', '=', $user_id];
            $where[] = ['client', '=',1];
            $auth = Db::name('user_auth')->where($where)->find();
            if($post['type']==2 && !$auth['openid']){
                return data_error('您还未绑定微信，无法进行提现');
            }
            if($post['type']==6 && !$user['zfb_data']){
                return data_error('您还未绑定支付宝，无法进行提现');
            }
            if($post['type']==5 && !$user['yhk_data']){
                return data_error('您还未绑定银行卡，无法进行提现');
            }
            $sn=createSn('withdraw_apply', 'sn');
            $money=$post['money']??'';
            if($money<=0){
                return data_error('请输入提现金额');
            }
            if($user['earnings']<$money){
                return data_error('您输入的金额大于了可提现金额');
            }
            //提现手续费
            $poundage = 0;
            // if ($post['type'] != WithdrawApply::TYPE_BALANCE){
            //     $poundage_config = ShopConfig::get('withdraw', 'poundage')??'0';
            //     $poundage = $money * $poundage_config / 100;
            // }

            $status=1;// 待提现
            $payment_time=0;//支付时间
            $payment_no='';
            if($post['type']==2){
                $post['account']=$auth['openid'];
                // $remark='收益提现到微信零钱';
                // $PayApi=new PayApi();
                // $data_error=$PayApi->preTransfers($sn,$money,$user['openid'],$remark);
                // return data_error($data_error['message']);
            }

            if($post['type']==6){
                $post['account']=$user['zfb_data'];
                $zfb_data=json_decode($user['zfb_data'],true);
                $data_error=AlipaySdk::carry_over($sn,$zfb_data['name'],$zfb_data['identity'],$money);
                if($data_error['code']==400){
                    return data_error($data_error['sub_msg']);
                }
                $status=3;//提现成功
                $payment_time=strtotime($data_error['trans_date']);
                $payment_no=$data_error['pay_fund_order_id'];
            }

            if($post['type']==5){
                $post['account']=$user['yhk_data'];
            }

            $data = [
                'sn' =>$sn,
                'user_id' => $user_id,
                'type' => $post['type'],
                'account' => $post['account'] ?? '',
                'real_name' => $post['real_name'] ?? '',
                'money' => $money,
                'left_money' => $money - $poundage,
                'money_qr_code' => $post['money_qr_code'] ?? '',
                'remark' => $post['remark'] ?? '',
                'bank' => $post['bank'] ?? '',
                'subbank' => $post['subbank'] ?? '',
                'poundage' => $poundage,
                'status' => $status,
                'payment_time'=>$payment_time,
                'payment_no'=>$payment_no,
                'create_time' => time(),
            ];
            $withdraw_id = Db::name('withdraw_apply')->insertGetId($data);

            //提交申请后,扣减用户的佣金
            $user->earnings = ['dec', $post['money']];
            $user->save();
            //增加佣金变动记录
            AccountLogLogic::AccountRecord(
                $user_id,
                $post['money'],
                2,
                AccountLog::withdraw_dec_earnings,
                '',
                $withdraw_id,
                $data['sn']
            );
            Db::commit();
            return data_success('', ['id' => $withdraw_id]);
        }catch (Exception $e){
            Db::rollback();
            return data_error($e->getMessage());
        }
    }


    //用户端提现记录
    public static function records($user_id, $get, $page, $size)
    {
        $count = Db::name('withdraw_apply')
            ->where(['user_id' => $user_id])
            ->count();

        $lists = Db::name('withdraw_apply')
            ->where(['user_id' => $user_id])
            ->page($page,$size)
            ->order('create_time desc')
            ->select();

        foreach ($lists as &$item){
            $item['desc'] = '提现至'.WithdrawApply::getTypeDesc($item['type']);
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            $item['transfer_time'] = date('Y-m-d H:i:s', $item['transfer_time']);
            $item['status_text'] = WithdrawApply::getStatusDesc($item['status']);
        }

        $data = [
            'list' => $lists,
            'page' => $page,
            'size' => $size,
            'count' => $count,
            'more' => is_more($count, $page, $size)
        ];
        return $data;
    }
}